package com.poet.df.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.poet.df.dbinfo.DbInfo;
import com.poet.df.dbinfo.pojo.Column;
import com.poet.df.dbinfo.pojo.PrimaryKey;
import com.poet.df.dbinfo.pojo.Table;

@Controller
@RequestMapping("/dyForm")
public class FormSubmitController {

	
	@Resource
	private DbInfo dbInfo;
	
	@RequestMapping("/processSubmit")
	@ResponseBody
	public String processSubmit(HttpServletRequest request,HttpServletResponse response){
		Map<String, String[]> requestParams = new HashMap<String, String[]>();
		requestParams.putAll(request.getParameterMap());
		// get tableName
		String tableName = requestParams.get("_TABLE_NAME_")[0];
		
		Table table = dbInfo.getTableInfo(tableName);
		if(table == null )
			return "出错！";
		
		requestParams.remove(tableName);
		
		// 排除主键自增
		for( PrimaryKey pk : table.getPrimaryKeys().values() ) {
			if(pk.getIsAutoIncrement()){ // 主键自增
				// 移除自增的主键
				requestParams.remove(table.getTableName()+"."+pk.getColumnName());
			}
		}
		
		// 判断操作是UPDATE还是INSERT
		boolean flag = true;
		for( PrimaryKey pk : table.getPrimaryKeys().values() ) {
			String key = table.getTableName()+"."+pk.getColumnName();
			if(requestParams.get(key) != null && !requestParams.get(key)[0].isEmpty()){
				flag &= true;
			} else {
				flag  = false;
				break;
			}
		} 
		
		String sqlOperation = flag == true ? "UPDATE" : "INSERT";
		
		// sql 参数
		Map<String, Object> sqlParams = new LinkedHashMap<String, Object>();
		for(Map.Entry<String, String[]> entry : requestParams.entrySet() ){
			String[] keyArray = entry.getKey().split("[.]");
			String[] valueArray = entry.getValue();
			
			String columnName = keyArray[keyArray.length-1];
			
			Column column = table.getColumns().get(columnName);
			
			if(column == null)
				continue;
			
			// 暂不考虑传入参数值为数组的情况
			if(valueArray.length != 1)
				return "参数值个数不为1！";
			
			String value = valueArray[0];
			
			sqlParams.put(columnName, convertType(column,value));
			
		}
		
		String sql = sqlOperation + " INTO " + table.getTableName();
		sql += "(";
		for( String key : sqlParams.keySet() ) {
			sql += key+",";
		}
		sql = sql.substring(0,sql.length()-1);
		sql += ") VALUES (";
		
		for( String key : sqlParams.keySet() ) {
			sql += "?,";
		}
		sql = sql.substring(0,sql.length()-1);
		sql += ")";
		
		System.out.println("\n"+sql+"\n");
		int count = 0;
		try ( Connection connection = dataSource.getConnection();
				PreparedStatement pst = connection.prepareStatement(sql)){
			int i = 0;
			for( Object value : sqlParams.values() ) {
				pst.setObject(++i, value);
			}
		 	count = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return String.valueOf(count);
	}
	
	@Resource
	private DataSource dataSource;
	
	private Object convertType(Column column,String value){
		Object result = value;
//		int sqlType = column.getDataType();
//		if(sqlType == Types.VARCHAR || sqlType == Types.CHAR || sqlType == Types.LONGNVARCHAR){
//			return value;
//		}
			
		return result;
	}
	
	
}
